package com.agile.leetcode.tomcat.netty;

import com.agile.leetcode.tomcat.abstractservlet.MyHttpServlet;
import com.agile.leetcode.tomcat.servletscanner.AddressScanner;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;

import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/9 17:45
 */
public class MyHandler extends ChannelInboundHandlerAdapter {
    static {
        AddressScanner.scan("com.agile.leetcode.tomcat");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 拿到request
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;
            NettyRequest request = new NettyRequest(ctx, req);
            // 构建response
            NettyResponse response = new NettyResponse(ctx, req);
            // 执行servlet
            doServlet(request, response);
        }

    }

    private void doServlet(NettyRequest request, NettyResponse response) throws IllegalAccessException, InstantiationException {
        // 拿到uri
        String url = request.getUrl();
        // 拿到方法
        String method = request.getMethod();
        // 拿到地址
        Map<String, Class> address = AddressScanner.getAddress();
        // 截取
        Class clazz = address.get(url);
        if (clazz != null) {
            MyHttpServlet httpServlet = (MyHttpServlet) clazz.newInstance();
            httpServlet.service(request, response);
        }
    }
}
